import axios from 'axios'
import router from '../router'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken, setToken, removeToken } from '@/utils/auth'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    if (store.getters.token) {
      // 让每个请求携带token-- ['X-Litemall-Admin-Token']为自定义key 请根据实际情况自行修改
      config.headers['Authorization'] = getToken()
    }
    if (config['service_module']) {
      let service_module = config['service_module']
      let url1 = config.baseURL + service_module
      config.baseURL = url1.toString().replace('/payment-cloud-user', '')
    }
    // if (config.url.indexOf("sys/dict/getDictItems") < 0) {
    //   config.params = {
    //     _t: Date.parse(new Date()) / 1000,
    //     ...config.params
    //   }
    // }
    return config
  },
  error => {
    // Do something with request error
    console.log('request', error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    console.log('interceptors', response)
    console.log('http状态status', response.status)
    const res = response.data
    // if (res.code !== 200) {
    //   MessageBox.alert('系统未登录，请重新登录', '错误', {
    //     confirmButtonText: '确定',
    //     type: 'error'
    //   }).then(() => {
    //     store.dispatch('FedLogOut').then(() => {
    //       location.reload()
    //     })
    //   })
    //   return Promise.reject('error')
    // }
    if (res.code !== 200) {
      Message({
        message: res.message || '系统异常，请稍候刷新重试！',
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject('error')
    } else {
      return response
    }
  }, error => {
    console.log('error', error)// for debug
    // console.log('respondata',error.data)// for debug
    console.log('responresponse', error.response.status)// for debug
    console.log('error.response.error', error.response.error)// for debug
    console.log('error_description', error.response.data.error_description)// for debug
    if (error.response.status === 401&&error.response.data.error==='invalid_token'||error.response.data.error==='unauthorized') {
      MessageBox.alert('登录失效，请点击确定重新登录！', '重新登录', {
        confirmButtonText: '确定',
        type: 'error'
      }).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      })
      return
    }
    Message({
      message: error.response.data.message || error.response.data.error_description||"系统异常，请稍候刷新重试！",
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  })

export default service
